

let root = {
  val:1,
  left: {
    val:2,
    left:{
      val:4,
      left:null,
      right:null
    },
    right:{
      val:5,
      left:null,
      right:null
    }
  },
  right: {
    val: 3,
    left: {
      val:6,
      left: null,
      right: null
    },
    right: {
      val:7,
      left:null,
      right:null
    }
  }
}
function TreeNode(val,left,right){
  this.val = (val===undefined ? 0 : val)
  this.left = (left===undefined ? null : left)
  this.right = (right===undefined ? null : right)
}

function test(root){
  if(!root) return root;
  let stack = [root];

  while(stack.length){
      const size = stack.length;
      for(let i =0;i<size;i++){
          let q = stack.shift();
          if(i<size-1){
            q.next = stack[0];
          }
          q.left && stack.push(q.left);
          q.right && stack.push(q.right);
      }
  }
  return root;
}
console.log(JSON.stringify(test(root),null,4));

